﻿<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<title>数据库详细信息</title>
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1" />

<link href="${mvcPath}/dacp-view/aijs/css/ai.css" type="text/css" rel="stylesheet" />
<style>
.media, .media-body {
	overflow: inherit;
	zoom: 1;
}

.list-group-item.active .dropdown-menu a {
	color: black;
}

small {
	font-size: 9px;
}
.fuelux .wizard {
	border-right: 0px;
	border-bottom: 1px solid #eee;
	box-shadow: 0 0px 0px;
	background-color: transparent;
	box-shadow: none;
	border-radius: 0px;
}

.wrapper {
	padding: 1px 15px 15px 15px;
}

.panel-body {
	padding: 2px 0px 5px 0px;
}
</style>
<script type="text/javascript" src="${mvcPath}/dacp-lib/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/underscore/underscore-min.js"></script>

<script src="${mvcPath}/dacp-lib/cryptojs/aes.js" type="text/javascript"></script>
<script src="${mvcPath}/crypto/crypto-context.js" type="text/javascript"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.core.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.field.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.jsonstore.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.grid.js"></script>
 
<script src="${mvcPath}/dacp-view/aijs/js/ai.treeview.js"> </script>
<script src="${mvcPath}/dacp-res/catalog/common/js/ai.meta.widget.js"></script>
<style>
.media, .media-body {
	overflow: inherit;
	zoom: 1;
}

.list-group-item.active .dropdown-menu a {
	color: black;
}

small {
	font-size: 9px;
}
 
.wrapper {
	padding: 1px 15px 15px 15px;
}
 
a.plan {
	font-size: 14px;
}

a.task {
	font-size: 13px;
}

.toolbar {
	margin-top: 10px;
	margin-bottom: 10px;
}

.toolbar .form-control {
	display: inline;
	padding: 1px 2px;
}

.toolbar button {
	margin-left: 10px;
}
.panel .table-striped > thead th {
    background-color: #36B0C8;
}
td{
	word-break:break-all;
}
.form-horizontal .form-group {
    margin-left: 0px;
    margin-right: 0px;
}
</style>

 
<script>
 $(document).ready(function() { 
 	var objtype="DATABASE";
 	
 	var objcode=paramMap.objname||'METADB';
 	
 	var objtabname="";
 	var xmlid=paramMap.xmlid;
 	var f = false;
 	var f_batch=false;
 	 
 	var metasoft=new AI.Meta(objtype);
 	
 	function buildDbBaseInfo(){
 		var objAttrStore=ai.getStoreData("select * from metaobjcfg where objtype='DATABASE' order by seq");
 		var objDataStore=ai.getStoreData("select * from metadbcfg where xmlid='"+xmlid+"'");
 		var html = '<fieldset> <table class="table"> <tbody>';
 		var objdbRec=objDataStore[0];
 		for(var i=0;i<objAttrStore.length;i++){
 			var objAttrItem = objAttrStore[i];
 			if(objAttrItem.INPUTTYPE=="password"){
 				html+='<tr > <th class="strong w-80px"> '+objAttrItem.ATTRCNNAME+'</th><td>******** </td></tr>';
 			}
 		    else if(objAttrItem.ATTRNAME=="DBUSAGE"){
				if(objdbRec[objAttrItem.ATTRNAME]=="1"){
					html+='<tr > <th class="strong w-80px"> '+objAttrItem.ATTRCNNAME+'</th><td>系统管理 </td></tr>';
				}else if(objdbRec[objAttrItem.ATTRNAME]=="2"){
					html+='<tr > <th class="strong w-80px"> '+objAttrItem.ATTRCNNAME+'</th><td>生产应用</td></tr>';
 				}
 			}else{
 				var value=objdbRec[objAttrItem.ATTRNAME];
				if(value==null||value=='undefined'){
					value='未知';
				}
				if(value.length>25){
					value=value.substring(0,25)+"...";
				}
				html+='<tr> <th class="strong w-80px"> '+objAttrItem.ATTRCNNAME+'</th><td>'+value+' </td></tr>';
 			}	
 		};
         html+='</tbody></table></fieldset>';              
         $("#dbbaseinfo").empty().append(html);                 
 	};

 	var dbUserInfoStore;
 	var dbUserInfoGrid;
 	function buildDBUserinfo(){
 		dbUserInfoStore =  new AI.JsonStore({
                sql:"select DBNAME,CNNAME,DBTYPE,JNDINAME,USERNAME,PASSWORD,TBSPACE,STATE,URL,LOGIC_DBNAME from data_trans_database where TEAM_CODE is null and LOGIC_DBNAME='"+objcode+"'",
                pageSize:10,
                key:"DBNAME",
                pageSize:-1,
                table:"data_trans_database"
      });
      var columns=[ { header : "账号", dataIndex : "USERNAME", headerAlign : "center", width : "100" },
						{ header : "账号说明", dataIndex : "CNNAME", headerAlign : "center", width : "150" },
						{ header : "密码", dataIndex : "PASSWORD", headerAlign : "center", width : "120",render:function(){
							  return "*******"
							} },
						{ header : "使用空间", dataIndex : "TBSPACE", headerAlign : "center", width : "120" },
						{ header : "JNDI名称", dataIndex : "JNDINAME", headerAlign : "center", width : "120" },
						//{ header : "可用CPU", dataIndex : "", headerAlign : "center", width : "120" },
						//{ header : "可用内存", dataIndex : "", headerAlign : "center", width : "120" },
						{ header : "状态", dataIndex : "STATE", headerAlign : "center", width : "120" }
      ]
 		var gridcfg = ({
								id : 'DBUserinfo',
								containerId : 'dbuserinfo',
								store : dbUserInfoStore,
								//sql:sql,
								showcheck : 'true',
								columns : columns
							});

							$('#dbuserinfo').empty();
							dbUserInfoGrid = new AI.Grid(gridcfg);
 	}; 
   function buildDbExtendInfo(caneditable){
		 var sql="SELECT XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, REMARK,ITEMCODE FROM metaobj_property where xmlid='"+objcode+"' order by itemcode";

		 dbExtendstore=  new AI.JsonStore({
                sql:sql,
                pageSize:10,
                key:"XMLID,PRO_KEY",
                pageSize:-1,
                table:"METAOBJ_PROPERTY"  
      });
      function proValRender(row, col){
			var val = row[col.dataField] || "";
			return '<input field="'+col.dataField+'" value="'+val+'" />';
		};
		var config = {
			id : "dbextendInfo",
			width : "100%",
			renderTo : "dbextendInfo",
			headerAlign : "left",
			headerHeight : "30",
			dataAlign : "left",
			indentation : "10",
			hoverRowBackground : "true",
			folderColumnIndex : "0",
			itemClick : itemClickEvent,
			showcheck:false,
			columns : [  
				{headerText : "KEY", dataField : "PRO_KEY", headerAlign : "center", width : "120" }, 
				{headerText : "名称", dataField : "PRO_NAME", headerAlign : "center", width : "80", dataAlign : "center", width : "100"}, 
				{headerText : "值", dataField : "PRO_VALUE", headerAlign : "left", width : "320", dataAlign : "center", width : "100",editable:caneditable}, 
				{headerText : "备注", dataField : "REMARK", headerAlign : "center", dataAlign : "center", width : "100"}
			],
			keyfield : "PRO_KEY",
			pkeyfield : "PARENTCODE",
			titlefield : "PRO_NAME",
			iconfield : "",
			//sql : sql,
			store:dbExtendstore,
			subtype : 'treegrid'
		};
		function itemClickEvent(id, index, data) {
			return;
			console.log(
					id + ", " + index + ", "
							+ TreeGrid.json2str(data));
		}
 
		//创建一个组件对象
		$("#dbextendInfo").empty();
		var treeGrid = new TreeGrid(config);
		treeGrid.show();
       ////相关操作
       /*
	    $("#dbextendInfo td input").change(function(){
	    	var val=($(this).val());
	    	var field=$(this).attr("field");
	    	console.log(field,val);
	    	console.log(dbExtendstore.curRecord);
	    	if(dbExtendstore.curRecord) dbExtendstore.curRecord.set(field,val);
	    	alert (dbExtendstore.curRecord.get('PRO_VALUE'));
	    	 
	    });
	    */
	    //编辑全部时,使输入框填充td
	    if(caneditable){
			$('#dbextendInfo td input[type="text"]').width("100%");
		}
	};
  
	function buildDataStruct(caneditable){

		 var sql="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+objcode+"'"; 

		 dbstructstore=  new AI.JsonStore({
                sql:sql,
                pageSize:10,
                key:"RULECODE",
                pageSize:-1,
                table:"METADB_STRUCT"  
      });
		var config = {
			id : "datastruct",
			width : "800",
			renderTo : "datastruct",
			headerAlign : "left",
			headerHeight : "30",
			dataAlign : "left",
			indentation : "20",
			showcheck: 'true',
			//folderOpenIcon: "images/folderOpen.gif",
			//folderCloseIcon: "images/folderClose.gif",
			//defaultLeafIcon: "images/defaultLeaf.gif",
			hoverRowBackground : "true",
			folderColumnIndex : "1",
			itemClick : itemClickEvent,
			columns : [ 
				{headerText : "名称", dataField : "RULECODE", headerAlign : "center", width : "120" }, 
				//{headerText : "中文名", dataField : "PARENTCODE", headerAlign : "center", width : "80" }, 
				{headerText : "中文名称", dataField : "RULENAME", headerAlign : "center", width : "220", dataAlign : "center", width : "100",editable:caneditable}, 
				{headerText : "类型", dataField : "RULETYPE", headerAlign : "center", width : "80", dataAlign : "center", width : "100",editable:caneditable},
				{headerText : "可包含对象", dataField : "FUNC_ID", headerAlign : "center", width : "120", dataAlign : "center", width : "100",editable:caneditable} 
				//,{headerText : "命名约束类型", dataField : "FUNC_NAME", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
				//{headerText : "命名规则", dataField : "RULEDEF", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
				//{headerText : "英文简称", dataField : "RULELEVEL", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
				 
			],
			keyfield : "RULECODE",
			pkeyfield : "PARENTCODE",
			titlefield : "RULENAME",
			iconfield : "",
			//sql : sql,
			store:dbstructstore,
			subtype : 'treegrid'
		};
		function itemClickEvent(id, index, data) {
			console.log(
					id + ", " + index + ", "
							+ TreeGrid.json2str(data));
		}

		/*
			通过指定的方法来自定义栏数据
			此渲染方式暂时屏蔽
		 */
		function customCheckBox(row, col) {
			return "<input type='checkbox'>";
		}
 

		function customLook(row, col) {
			return "<a href='' style='color:blue;'>查看</a>";
		}

		//创建一个组件对象
		$("#datastruct").empty();
		var treeGrid = new TreeGrid(config);
		treeGrid.show();
		//将输入框的宽度设置为填充父级
 		if(caneditable){
			$('#datastruct td input[type="text"]').width("100%");
		}
		//将类型渲染为下拉框形式
		$("#datastruct tr").each(function(){
			var pid = $(this).attr("pid") + "";
			var pidIndex = pid.indexOf("TRdatastruct");
			var rule_type = $(this).children("td:last-child").prev().text();
			if(pidIndex != -1){
				var obj = $(this).attr("data");
				obj = eval("("+obj+")");
				var selectID = obj.RULECODE + "Select";
				var defaultVal = obj.RULETYPE + "";
				if(caneditable){ 
					if(pid != "TRdatastruct"){
						var ruleTypeSelect = $('<select style="width:100%;" id='+selectID+'></select>');
						//ruleTypeSelect.append('<option value=""></option>');
						ruleTypeSelect.append('<option value="TOPICNAME">主题</option>');
						ruleTypeSelect.append('<option value="LEVELNAME">层次</option>');
						$(this).children("td:last-child").prev().empty();
						ruleTypeSelect.val(defaultVal);
						$(this).children("td:last-child").prev().append(ruleTypeSelect);
					}
				}else{
					switch(rule_type){
						case 'LEVELNAME': 
							$(this).children("td:last-child").prev().text("层次");
							break;
						case 'TOPICNAME': 
							$(this).children("td:last-child").prev().text("主题");
							break;
						default : 
							$(this).children("td:last-child").prev().text("");
							break;
					}
				}
			}
		});
	};
    buildDbBaseInfo();
    // buildDBUserinfo();
	buildDbExtendInfo();
	buildDataStruct();
	 $("#editObjInfo").click(function(){
        metasoft.editMetaObjBaseInfo({objtype:objtype,objid:xmlid,storeAtMetaObj:'n',aftSave:buildDbBaseInfo}); 
    });
     $("#editImportTpl").unbind().click(function(){
       	 var sql="delete from metaobj_property where xmlid='"+objcode+"'";
       	 ai.executeSQL(sql);
       	/*  var sql="insert into metaobj_property(XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode)"+
              "SELECT '"+objcode+"',PARACODE,PARATEXT,PARENTCODE, PARANAME, REMARK,ATTRCODE FROM metaobjmodel_def where OBJTYPE='"+objtype+"' and REFNAME='public' order by ATTRCODE";
          ai.executeSQL(sql);   */ 
          var objDatabaseStore=ai.getStoreData("select * from metadbcfg where xmlid='"+xmlid+"'");          
          var sql="";    
          var alertMessage="未找到匹配数据库类型的模板，导入的是通用模板!";
          if(objDatabaseStore.length>0){
        	  var databaseType=objDatabaseStore[0]['ALIAS'];
        	  if(databaseType==null||databaseType==""){       		  	      
        	      sql="insert into metaobj_property(XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode)"+
                  "SELECT '"+objcode+"',PARACODE,PARATEXT,PARENTCODE, PARANAME, REMARK,ATTRCODE FROM metaobjmodel_def where OBJTYPE='"+objtype+"' and REFNAME='public' order by ATTRCODE";
        	  }else{
        		  var objModelData=ai.getStoreData("SELECT '"+objcode+"',PARACODE,PARATEXT,PARENTCODE, PARANAME, REMARK,ATTRCODE FROM metaobjmodel_def where OBJTYPE=CONCAT('DATABASE-','"+databaseType+"') and REFNAME='public' order by ATTRCODE");
        		  if(objModelData.length>0){
        			  sql="insert into metaobj_property(XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode)"+
                      "SELECT '"+objcode+"',PARACODE,PARATEXT,PARENTCODE, PARANAME, REMARK,ATTRCODE FROM metaobjmodel_def where OBJTYPE=CONCAT('DATABASE-','"+databaseType+"') and REFNAME='public' order by ATTRCODE";
        			  alertMessage="导入模板成功!"; 
        		  }else{
        			  sql="insert into metaobj_property(XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode)"+
                      "SELECT '"+objcode+"',PARACODE,PARATEXT,PARENTCODE, PARANAME, REMARK,ATTRCODE FROM metaobjmodel_def where OBJTYPE='"+objtype+"' and REFNAME='public' order by ATTRCODE";
        		  }
        	  }
          }else{
        	  sql="insert into metaobj_property(XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode)"+
              "SELECT '"+objcode+"',PARACODE,PARATEXT,PARENTCODE, PARANAME, REMARK,ATTRCODE FROM metaobjmodel_def where OBJTYPE='"+objtype+"' and REFNAME='public' order by ATTRCODE";
          }
          
          ai.executeSQL(sql);
          buildDbExtendInfo();
          $("#editDbExtendItem").html("<i class='glyphicon glyphicon-user'></i>"+"编辑");
     	  f=false;
     	  alert(alertMessage);
          
       });
     $("#similaryImportItem").click(function(){
    	 var sql="SELECT * FROM metaobj_property WHERE xmlid IN (SELECT dbname FROM metadbcfg WHERE alias=(SELECT alias FROM metadbcfg WHERE dbname='"+objcode+"') AND dbname <> '"+objcode+"')";
    	 var dataStore=ai.getStoreData(sql);
    	 if(dataStore.length>0){    		 
    		 var delSql="delete from metaobj_property where xmlid='"+objcode+"'";
    		 ai.executeSQL(delSql);
    		 var insertSql="insert into metaobj_property(XMLID, PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode) "+
    		         "SELECT '"+objcode+"', PRO_KEY, PRO_VALUE, PARENTCODE, PRO_NAME, remark,itemcode FROM metaobj_property WHERE xmlid =(SELECT dbname FROM metadbcfg WHERE alias=(SELECT alias FROM metadbcfg WHERE dbname='"+objcode+"' ) AND dbname <> '"+objcode+"' LIMIT 1);";
    		 ai.executeSQL(insertSql); 
    		 buildDbExtendInfo();
    		 $("#editDbExtendItem").html("<i class='glyphicon glyphicon-user'></i>"+"编辑");
    	   	 f=false;
             alert("导入成功");
    	 }else{
    		 alert("没有相似的模板导入，请使用按模板导入！");
    	 }
     });
   $("#saveDbExtendItem").click(function(){
   		$("#dbextendInfo tr").each(function(){
   			var pid = $(this).attr("pid") + "";
			var pidIndex = pid.indexOf("TRdbextendInfo");
			if(pidIndex!=-1 && pid!='TRdbextendInfo'){
				var pro_value = $(this).children("td:last-child").prev().children("input").val();
				var obj = $(this).attr("data");
				obj = eval("("+obj+")");
				var key = obj.XMLID+","+obj.PRO_KEY;
   				dbExtendstore.getRecordByKey(key).set("PRO_VALUE",pro_value);
			}
   		});
   		var result =dbExtendstore.commit();
   	    console.log(result);
   	    //保存后刷新数据
   		buildDbExtendInfo();
   		$("#editDbExtendItem").html("<i class='glyphicon glyphicon-user'></i>"+"编辑");
   		f=false;
   		alert("保存成功");
   });
  
   $("#editDbExtendItem").click(function(){
	 if(!f){
		$("#editDbExtendItem").html("<i class='glyphicon glyphicon-user'></i>"+"取消"); 
		buildDbExtendInfo(true);
		f=true;
	 }else{
		$("#editDbExtendItem").html("<i class='glyphicon glyphicon-user'></i>"+"编辑"); 
		buildDbExtendInfo();
		f=false;
	 }
   });

	//新增/修改用户Item配置
	var dbAcountItems;
	function bulidDBAcountFormCfg(readOnly){
		dbAcountItems = [
			{type:'text',label:'账号',notNull:'N',fieldName:'USERNAME',width:320,isReadOnly:readOnly},
			{type:'password',label:'密码',fieldName:'PASSWORD',width:320},
			{type:'text',label:'使用空间',fieldName:'TBSPACE',width:320},
			{type:'text',label:'URL',fieldName:'URL',notNull:'N',width:320},
			{type:'text',label:'JNDI名称',fieldName:'JNDINAME',width:320,notNull:'N'},
			{type:'combox',label:'状态',fieldName:'STATE',storesql:'on,有效|off,失效',value:"on",width:320}
			// {type:'textarea',label:'账号说明',fieldName:'CNNAME',width:320}
		];
	}
	
	function buildUserInfoForm(readOnly){
		var title = "修改数据库用户";
		if(readOnly == 'n'){
	  		title = "新增数据库用户";
		}
		bulidDBAcountFormCfg(readOnly);
  		ai.openFormDialog(title,dbAcountItems,dbUserInfoCallBack,dbUserInfoStore);
	}
	//新建用户
	var readOnly = "n";
	$("#adddbuserInfo").click(function(){
		dbUserInfoStore.cache.save = [];
		readOnly = "n";

		var dbBaseInfoStore = new AI.JsonStore({
			sql: " select DBNAME,CNNAME,URL,JNDINAME from METADBCFG where DBNAME ='"+objcode+"' ",
            pageSize:10,
            key:"DBNAME",
            table:"METADBCFG"
		});

		var _record = dbUserInfoStore.getNewRecord();
  		_record.set("LOGIC_DBNAME",objcode);
  		_record.set("CNNAME",dbBaseInfoStore.getAt(0).get("CNNAME"));	
  		_record.set("URL",dbBaseInfoStore.getAt(0).get("URL"));
  		dbUserInfoStore.curRecord = _record;
		buildUserInfoForm(readOnly);
	});
	//修改用户
	var prePWD = "";
	$("#updatedbuserInfo").click(function(){
		readOnly = "y";
		var selectedRows = dbUserInfoGrid.getCheckedRows();
		if(selectedRows.length < 1){
			alert("请选择要修改的行！");
			return false;
		}else if(selectedRows.length > 1){
			alert("仅能修改一行！");
			return false;
		}
		dbUserInfoStore.curRecord = selectedRows[0];
		prePWD = selectedRows[0].get("PASSWORD");
		buildUserInfoForm(readOnly);
	});
	var dbUserInfoCallBack = function(){
		var _record = dbUserInfoStore.curRecord;

		if(!_record.get("USERNAME") || !_record.get("JNDINAME") || !_record.get("URL")){
			alert("请填写必填项！");
			return false;
		}
		//判断当前用户是否已经创建
		if(readOnly == "n"){
			var userIsExistStore = ai.getJsonStore(" select DBNAME,LOGIC_DBNAME,USERNAME from data_trans_database where TEAM_CODE is null and LOGIC_DBNAME='"+objcode+"' and UPPER(USERNAME)='"+_record.get("USERNAME").toUpperCase()+"'");
			if(userIsExistStore.getCount() > 0){
				alert("当前用户已创建！");
				return false;
			}
		}
		if(!_record.get("PASSWORD")){
			if(confirm("确认不设置密码？")){
				if (readOnly == "n") {
					_record.set("DBNAME",_record.get("LOGIC_DBNAME")+_record.get("USERNAME"));
					dbUserInfoStore.add(_record);
				}
				dbUserInfoStore.commit();
				// buildDBUserinfo();
			}else{
				return false;
			}
		}else{
			if(prePWD != _record.get("PASSWORD")){
				var URL="/"+contextPath+"/crypto/encrypt/des?message="+_record.get("PASSWORD");
				var obj=ai.remoteData(URL);
				_record.set("PASSWORD",obj);
			}
			if (readOnly == "n") {
				_record.set("DBNAME",_record.get("LOGIC_DBNAME")+_record.get("USERNAME"));
				dbUserInfoStore.add(_record);
			}
			dbUserInfoStore.commit();
			// buildDBUserinfo();
		}
	}

	//删除用户
	$("#deldbuserInfo").click(function(){
		var checkedRows = dbUserInfoGrid.getCheckedRows();
		if(checkedRows.length<1){
			alert("请选择要删除的行！");
			return false;
		}
		if(confirm("确认删除勾选的项吗？")){
			for(var i=0;i<checkedRows.length;i++){
				dbUserInfoStore.remove(checkedRows[i]);
			}
			dbUserInfoStore.commit();
			dbUserInfoStore.select();
			alert("更新数据成功！");
		}
	});


   var dbFrameItems;
   //判断当前是否为新增操作
   var isCreate = true;
   function buildDBFrameFormCfg(isAdd){
   		dbFrameItems = [
			{type:'text',label:'规则编号',fieldName:'RULECODE',notNull:'N',width:320,isReadOnly:isAdd},
			{type:'text',label:'上级编号',fieldName:'PARENTCODE',width:320,isReadOnly:isAdd},
			{type:'text',label:'名称',fieldName:'RULENAME',notNull:'N',width:320},
			{type:'combox',label:'节点类型',fieldName:'RULETYPE',notNull:'N',storesql:'LEVELNAME,层次|TOPICNAME,主题',width:320},
			{type:'checkbox',label:'可包含对象',fieldName:'FUNC_ID',storesql:"select OBJTYPE,OBJNAME from METAOBJMODEL where PARENTCODE is not null and parentcode<>'META-OTHER' and parentcode<>'META' and STATE = 'Y' order by ORDSEQ asc ",width:320},
			//{type:'pick-grid',label:'可包含对象',fieldName:'FUNC_ID',storesql:'select objtype,objname from metaobjmodel where using_stat=\'Y\'',width:320}
			//,{type:'text',label:'命名约束类型',fieldName:'FUNC_NAME',width:320},
			//{type:'text',label:'命名规则',fieldName:'RULEDEF',width:320},
			//{type:'text',label:'英文简称',fieldName:'RULELEVEL',width:320}
		];
   }
   
   //判断当前操作是否为批量编辑
   var isBachUpdate = false;
   $("#batchEditDataStruct").click(function(){
	   if(!f_batch){
		   $("#batchEditDataStruct").html("<i class='glyphicon glyphicon-user'></i>"+"取消编辑");
		   f_batch=true;
		   isBachUpdate = true;
	       buildDataStruct(true);
	   }else{
		   $("#batchEditDataStruct").html("<i class='glyphicon glyphicon-user'></i>"+"批量编辑");
		   f_batch=false;
		   isBachUpdate = false; 
		   buildDataStruct();
	   }
   		
   });
   $("#saveDataStruct").click(function(){
	   /*增加功能满足批量编辑后，后台FUNC_NAME跟着FUNC_ID变更；增加可包含对象的正误判断2016-04-11*/
	   	var funcStore=new AI.JsonStore({
			sql:"select OBJTYPE,OBJNAME from METAOBJMODEL",
			table:"METAOBJMODEL",
			pageSize:-1
		});
	   	var funcname ="";
			for(i=0;i<dbstructstore.getCount();i++){
				var funcid = dbstructstore.getAt(i).get("FUNC_ID");
				if(funcid){
					funcid = funcid.split(",");
					for(k=0;k<funcid.length;k++){
						var flag = true;
						for(var j=0;j<funcStore.getCount();j++){
							if(funcid[k].trim()==funcStore.getAt(j).get("OBJTYPE").trim()){
								funcname += getFuncName(funcStore,funcid[k].trim()) + ",";
								flag = true;
								break;
							}else{
								flag= false;
							}
						}
						if(flag==false){
							alert("无法识别的可包含对象，请检查后重新输入");
							return false;
						}
					}
					dbstructstore.getAt(i).set("FUNC_NAME",funcname);
					funcname = "";
				}
			}
   		if(isBachUpdate){
   			$("#datastruct tr").each(function(){
   				var pid = $(this).attr("pid") + "";
				var pidIndex = pid.indexOf("TRdatastruct");
				var rule_type = $(this).children("td:last-child").prev().text();
				if(pidIndex != -1 && pid != "TRdatastruct"){
					var obj = $(this).attr("data");
					obj = eval("("+obj+")");
	   				var key = obj.RULECODE;
	   				var value = $("#"+key+"Select").val();
	   				dbstructstore.getRecordByKey(key).set("RULETYPE",value);
				}
   			});
   		}
   		dbstructstore.commit();
   		buildDataStruct();
   		$("#batchEditDataStruct").html("<i class='glyphicon glyphicon-user'></i>"+"批量编辑");
		f_batch=false;
   		alert("保存成功");
   });
   function getFuncName(store,func_id){
   		for(var i=0;i<store.getCount();i++){
   			if(store.getAt(i).get("OBJTYPE").trim()==func_id){
   				return store.getAt(i).get("OBJNAME");
   			}else{
   				continue;
   			}
   		}
   		return "...";
   }
   $("#initDataStruct").click(function(){
   	var curRecord = dbstructstore.curRecord;
   	isCreate = true;
   	buildDBFrameFormCfg('n');
   	ai.openFormDialog("新增主题规则",dbFrameItems,callBack,null);
   	if(curRecord){
   		$("#RULECODE").val(curRecord.get("RULECODE")+"_");
   		$("#PARENTCODE").val(curRecord.get("RULECODE"));
   	}else{
   		$("#RULECODE").val(objcode+"_");
   		$("#PARENTCODE").val("");
   	}
	$("#RULETYPE").val("LEVELNAME");
   });
   $("#editDataStruct").click(function(){
   		isCreate = false;
   		buildDBFrameFormCfg('y');
   		ai.openFormDialog("修改主题规则",dbFrameItems,callBack,dbstructstore);
   });
   var callBack =function(){
   	var rulecode = $("#RULECODE").val();
   	var parentcode = $("#PARENTCODE").val();
   	var rulename = $("#RULENAME").val();
	var ruletype = $("#RULETYPE").val();
	var func_id = "";
	var func_name="";
	var funcStore=new AI.JsonStore({
		sql:"select OBJTYPE,OBJNAME from METAOBJMODEL",
		table:"METAOBJMODEL",
		pageSize:-1
	});
	var str=document.getElementsByName("FUNC_ID");
	for(var i=0;i<str.length;i++){
		if(str[i].checked){
			func_id += str[i].value + ",";
			func_name += getFuncName(funcStore,str[i].value.trim()) + ",";
		}
	}
	func_id = func_id.substring(0,func_id.lastIndexOf(","));
	func_name = func_name.substring(0,func_name.lastIndexOf(","));
	var rec = dbstructstore.getNewRecord();
	rec.set("XMLID",xmlid);
   	rec.set("DBNAME",objcode);
   	rec.set("RULECODE",rulecode);
   	rec.set("PARENTCODE",parentcode);
   	rec.set("RULENAME",rulename);
   	rec.set("RULETYPE",ruletype);
   	rec.set("FUNC_ID",func_id);
   	rec.set("FUNC_NAME",func_name);
   	//先校验上级编号是否是存在
   	if(parentcode){
   		var isParent = dbstructstore.getRecordByKey(rec.get("PARENTCODE"));
   		if(isParent || parentcode==""){
   			
   		}else{
   			alert("父级编号不存在");
   			return false;
   		}
   	}
   	//再校验当前编号是否按照规则
   	if(rulecode && rulename && ruletype){
   		if(isCreate){
   			var oldStructDataStoreSql = "select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNc_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct";
   			var oldStructDataStore = new AI.JsonStore({
   				sql:oldStructDataStoreSql,
                key:"RULECODE",
                pageSize:-1,
                table:"METADB_STRUCT"
   			});
   			var isExist = oldStructDataStore.getRecordByKey(rulecode);
	   		if(isExist){
	   			alert("当前规则编号已存在");
	   			return false;
	   		}
   		}
   		var _index = rulecode.lastIndexOf("_");
   		var codePre = rulecode.substr(0,_index);
   		var codeEnd = rulecode.substr(_index+1,rulecode.length);
   		if(parentcode){
   			if(codePre != parentcode){
   				alert("编号需以父级编号为前缀");
   				return false;
   			}
   			if(!codeEnd){
   				alert("编号需以父级编号加+\"_\"+编号值组成");
   				return false;
   			}
   		}else{
   		/*校验是否以当前数据库名为前缀
   			if(codePre != objcode){
   				alert("编号需以当前数据库编号为前缀");
   				return false;
   			}
   			if(!codeEnd){
   				alert("编号需以当前数据库编号加+\"_\"+编号值组成！");
   				return false;
   			}
   		*/
   		}
   	}else{
   		alert("请填写带\" * \"的必填项！");
		return false;
   	}
   	if(isCreate){
   		dbstructstore.add(rec);
   	}else{
   		dbstructstore.curRecord.set("FUNC_NAME",func_name);
   	}
   	dbstructstore.commit();
   	buildDataStruct();
   	$("#batchEditDataStruct").html("<i class='glyphicon glyphicon-user'></i>"+"批量编辑");
	f_batch=false;
   }
   $("#deleteDataStruct").click(function(){
   		var curRecord = dbstructstore.curRecord;
   		var ruleCode = curRecord.get("RULECODE");
   		var checkCountSql = "select 1 from metadb_struct where PARENTCODE='"+ruleCode+"' and DBNAME='"+objcode+"'"; 
   		var _ds = ai.getJsonStore(checkCountSql);
			if(_ds.getCount() > 0){						
				alert("请先删除子节点数据!!");
				return;
			} 
			if(confirm("确定删除规则编码:"+ruleCode+"信息吗？")){
				dbstructstore.remove(curRecord);
				dbstructstore.commit();
				buildDataStruct();
			}
   });
    						 
   });
</script>
</head>
<body class="">
	<div class="container-fluid">
		<div class="row" style="display:none">
			<div class="alert alert-info">
				<button type="button" class="close" data-dismiss="alert">×</button>
				<i class="fa fa-info-sign"></i><strong>当前任务单提示!</strong><span
					id="flowuserInfo"> 你是个过客,只有浏览权限</span>
			</div>
		</div>
		<div class="row" id="taskInfo">
			<div class="col-sm-3" style="padding-left: 1px; padding-right: 1px">
				<h5> 数据库基本信息<small id='tip'> </small> </h5>
				<section class="panel panel-info portlet-item" style="opacity: 1; z-index: 0;">
					<header class="panel-heading"> 详细信息 </header>
					<div class="panel-body "
						style="width: 100%; height: auto; padding: 0px" id="dbbaseinfo">

					</div>
					<footer class="panel-footer"  > <a href="#" id="editObjInfo" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>编辑</a>  </footer>
				</section>
			</div>
			<div class="col-sm-9">

				<h5><span id="funaction">数据库分项详细信息</span></h5>

				<section class="panel panel-info">
					<header class="panel-heading">
						<span class="hidden-sm"> &nbsp; </span> <span id="taskname"
							style="float: left">详细信息</span>
						<ul class="nav nav-tabs pull-right">
					
							<li class="active"><a href="#tab1" data-toggle="tab"> <i class="fa fa-comments text-muted"> </i> 数据库扩展信息 </a></li>
							<li class=""><a href="#tab2" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 数据库架构 </a></li>
						</ul>

					</header>
					<div class="panel-body">
						<div class="tab-content">
							<div class="tab-pane active" id="tab1">
								<div class='toolbar'>
									<button id="editImportTpl" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>按模板导入</button>
									<button id="addDbExtendItem" class="btn btn-danger  btn-xs hide" enabled="">  <i class="glyphicon glyphicon-user"></i>增加</button>
									<button id="editDbExtendItem" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>编辑</button>
									<button id="deleteDbExtendItem" class="btn btn-danger  btn-xs hide" enabled="">  <i class="glyphicon glyphicon-user"></i>删除</button>
									<button id="saveDbExtendItem" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>保存</button>
									<!--<button id="similaryImportItem" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>相似模板导入</button>-->
								</div>
								<div class="panel-body" id="dbextendInfo"></div>
							</div>
							<div class="tab-pane" id="tab2">
								<div class='toolbar'>
									<button id="initDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>新增</button>
									<button id="batchEditDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>批量编辑</button>
									<button id="editDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>编辑当前</button>
									<button id="saveDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>保存</button>
									<button id="deleteDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>删除</button>
								
								 </div>
								<div id="datastruct"></div>
							</div>
						</div>
					</div>
				</section>
			</div>
		</div>
	</div>
 
</body>
</html>